package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.utils.Constants;
import cn.smbms.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.ibatis.jdbc.Null;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.Logger;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    private Logger logger;

    @RequestMapping("/toLogin")
    public String toLogin() {
        System.out.println("跳转到登录页面");
        return "/login";
    }

    @PostMapping("/login")
    public String Login(HttpServletRequest request, HttpSession session,
                        @RequestParam String userCode, @RequestParam String userPassword) {
        System.out.println("登录方法" + userCode + userPassword);
        User user = userService.Login(userCode, userPassword);
        if (null != user) {
            session.setAttribute(Constants.USER_SESSION, user);
            return "redirect:/user/toMain";
        } else {
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/user/toLogin";
    }

    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        ;
        if (session.getAttribute(Constants.USER_SESSION) == null) {
            return "redirect:/user/login";
        }
        return "/frame";
    }

    /**
     * 跳转到用户查询
     *
     * @param session
     * @return
     */
    @RequestMapping("/toUserList")
    public String toUserList(HttpSession session, Model model) {
        if (session.getAttribute(Constants.USER_SESSION) == null) {
            return "redirect:/user/login";
        } else if (session.getAttribute("roleList") == null) {
            List<Role> roleList = roleService.getRoleList();
            session.setAttribute("roleList", roleList);
            return "redirect:/user/getUserList";
        } else if (model.getAttribute("userList") == null) {
            return "redirect:/user/getUserList";
        }
        return "/sysUser/list";
    }

    @RequestMapping("/getUserList")
    public String getUserList(Model model, String userName, Integer userRole, Integer pageIndex) {
        System.out.println(userName);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(10);
        if (pageIndex != null) {
            pageSupport.setCurrentPageNo(pageIndex);
        } else {
            pageSupport.setCurrentPageNo(1);
        }
        pageSupport.setTotalCount(userService.getUserCount(userName, userRole));
        pageSupport.setPagelimit((pageSupport.getCurrentPageNo() - 1) * 10);
        List<User> list = userService.getUserList(userName, userRole, pageSupport);
        model.addAttribute("pageSupport", pageSupport);
        model.addAttribute("userList", list);
        return "/sysUser/list";
    }

    @PostMapping("/addUser")
    public String addUser(HttpServletRequest request, HttpSession session, String account,
                          String realName, String password, Integer sex, @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
                          String phone, String address, Integer roleId, @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws IOException {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        System.out.println("文件储存路径" + path);
        for (int i = 0; i < attachs.length; i++){
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()){
                if (i == 0){
                    errorInfo = "uploadFileError";
                }else if (i == 1){
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();  //原文件名
                System.out.println("原文件名" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName); //原文件后缀
                System.out.println("原文件后缀" + prefix);
                int filesize = 500000;
                if (attach.getSize() > filesize){
                    request.setAttribute(errorInfo,"上传大小不得超过500kb");
                    flag = false;
                }else if (prefix.equalsIgnoreCase("JPG")
                        || prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")){
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    File targetFile = new File(path);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    attach.transferTo(new File(targetFile, fileName));
                    if (i == 0){
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }else if (i == 1){
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    System.out.println("idPicPath:" + idPicPath);
                    System.out.println("workPicPath:" + workPicPath);
                } else {
                    request.setAttribute(errorInfo, "上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag){
            User user = new User();
            User createdUser = (User) session.getAttribute("user");
            user.setUserCode(account);
            user.setUserName(realName);
            user.setUserPassword(password);
            user.setGender(sex);
            user.setBirthday(birthday);
            user.setPhone(phone);
            user.setAddress(address);
            user.setUserRole(roleId);
            user.setCreatedBy(createdUser.getId());
            Date date = new Date();
            user.setCreationDate(date);
            user.setModifyBy(createdUser.getId());
            user.setModifyDate(date);
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);
            Boolean bool = userService.addUser(user);
            System.out.println("添加成功");

        }
        return "/sysUser/add";
    }

    @RequestMapping("/toAddUser")
    public String toAddUser(HttpSession session){
        if(session.getAttribute("user") != null){
            return "/sysUser/add";
        }
        return "redirect:/user/toLogin";
    }

    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account){
        System.out.println(account);
        HashMap<String,Object> resultMap = new HashMap<>();
        if(StringUtils.isNullOrEmpty(account)){
            resultMap.put("exist",1);
        }else {
            User user = userService.getUserByUserCode(account);
            if (null != user){
                resultMap.put("exist",1);
            }else {
                resultMap.put("exist",0);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @GetMapping("/getRoleList")
    public List<Role> getRoleList() {
        List<Role> roleList = roleService.getRoleList();
        return roleList;
    }

    @GetMapping("/deleteUser")
    public Object deleteUser(Integer userid){
        HashMap<String,Object> resultMap = new HashMap<>();
        User user = userService.getUserById(userid);
        System.out.println("删除");
        if (null != user){
            boolean flag = userService.deleteUser(userid);
            if (flag){
                System.out.println("成功删除");
                resultMap.put("delResult","true");
            }else{
                System.out.println("删除失败");
                resultMap.put("delResult","false");
            }
        }else {
            System.out.println("用户不存在");
            resultMap.put("delResult","notexist");
        }
        return JSON.toJSONString(resultMap);
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Model model,HttpSession session,Integer userid){
        if(session.getAttribute("user") != null){
            User user = userService.getUserById(userid);
                model.addAttribute("user",user);
                return "/sysUser/update";
        }
        return "redirect:/user/toLogin";
    }

    @PostMapping("/updateUser")
    public String updateUser(Model model,HttpSession session,
                             String account,String realName,
                             Integer sex,@DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
                             String phone,String address,
                             Integer roleId){
        User Admin = (User) session.getAttribute("user");
        User user = new User();
        user.setUserCode(account);
        user.setUserName(realName);
        user.setGender(sex);
        user.setBirthday(birthday);
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(roleId);
        user.setModifyBy(Admin.getId());
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        user.setModifyDate(date);
        Boolean flag = userService.updateUser(user);
        if (flag) {
            System.out.println("修改成功");
            return "redirect:/user/toUserList";
        }
        System.out.println("修改失败");
        return "/sysUser/update";
    }

    @PostMapping("/updateUserPassword")
    public String updateUserPassword(@RequestParam("id") Integer id, @RequestParam("newPassword") String newPassword){
        System.out.println("用户id:" + id + "新密码:" + newPassword);
        Boolean flag = userService.updateUserPassword(id,newPassword);
        if (flag){
            System.out.println("成功");
            return "frame";
        }
        return "/sysUser/updatePassword";
    }

    @ResponseBody()
    @GetMapping("/oldPasswordIf")
    public Object oldPasswordIf(HttpSession session,@RequestParam("oldpassword") String oldpassword,@RequestParam("newpassword") String newpassword){
        System.out.println("旧密码:" + oldpassword + "新密码:" + newpassword);
        HashMap<String,Object> map = new HashMap<>();
        if (null != session.getAttribute("user")){
            User user = (User) session.getAttribute("user");
            if (null != oldpassword){
                if (user.getUserPassword().equals(oldpassword)){
                    System.out.println("旧密码正确");
                    map.put("result","true");
                }else {
                    System.out.println("旧密码错误" + user.getUserPassword());
                    map.put("result","false");
                }
            }else {
                System.out.println("旧密码为空");
                map.put("result","error");
            }
        }else {
            System.out.println("session失效");
            map.put("result","sessionerror");
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping("/toUpdateUserPassword")
    public String toUpdateUserPassword(HttpSession session){
        if(session.getAttribute("user") != null){
            return "/sysUser/updatePassword";
        }
        return "redirect:/user/toLogin";
    }
}
